import { deviceMapServer, deviceDeployMap } from '@/api'
import QJDLIST from './qjd.json'
import { requireImg } from '@/utils/common'
import _turf from '@/utils/turfUtil'
import AirAnimation from '@/views/operation/js/airAnimation.js'
import { ref } from 'vue'
import Index from '../qjss/Index.vue'
import { useFlyNumStore, usePopStore } from '@/stores'
const flyNumStore = useFlyNumStore()
const popStore = usePopStore()

const airAnimation = new AirAnimation()

export function infrastructureInit() {
  addQjss()
}

const list = [
  [525899.28, 2498368, 63.54125],
  [526001.88, 2498501.6, 18.43939453125],
  [525953.8025, 2498758.88, 16.659306640625],
  [525761.7175, 2498826.4, 45.6002783203125],
  [525598.2725, 2498564.32, 22.7796923828125]
]
//图例列表
const LegendList = [
  {
    name: '文旅观光',
    img: '/poi/qjss_lenged_01.png'
  },
  {
    name: '直升机/evtol起降坪',
    img: '/poi/qjss_lenged_02.png'
  },
  {
    name: '物流运输',
    img: '/poi/qjss_lenged_03.png'
  },
  {
    name: '政务巡检',
    // img: '/poi/qjss_lenged_04.png'
    img: '/poi/qjss_jichao.png'
  },
  {
    name: '低空融合飞行验证',
    img: '/poi/qjss_lenged_05.png'
  },
  {
    name: '无人机机巢',
    img: '/poi/qjss_jichao.png'
  },
  {
    name: '无人机起降场',
    img: '/poi/qjss_lenged_04.png'
  }
]

const qjdevList = [
  {
    name: '直升机',
    img: '/poi/qjss_lenged_02.png'
  },
  {
    name: '无人机起降场',
    img: '/poi/qjss_lenged_04.png'
  },
  {
    name: '无人机机巢',
    img: '/poi/qjss_jichao.png'
  }
]

//图例列表
const flyLegendList = [
  {
    name: '4G/5G设备',
    img: '/poi/tdj_lenged_01.png'
  },
  {
    name: '5G-A设备',
    img: '/poi/tdj_lenged_02.png'
  },
  {
    name: '导航设备',
    img: '/poi/tdj_lenged_02.png'
  },
  {
    name: '光电探测设备',
    img: '/poi/tdj_lenged_03.png'
  },
  {
    name: '频谱探测设备',
    img: '/poi/tdj_lenged_04.png'
  },
  {
    name: 'AD5-B设备',
    img: '/poi/tdj_lenged_05.png'
  },
  {
    name: '低空雷达',
    img: '/poi/tdj_lenged_04.png'
  }
]

// 起降点模型
const qjdModel = [
  {
    name: '文旅观光',
    assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/TingJIPin1'
  },
  {
    name: '载人通勤',
    assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/TingJIPin2'
  },
  {
    name: '物流运输&政务巡检&低空融合飞行验证',
    assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/TingJIPin2'
  }
]
//添加起降设施点位
export async function addQjss() {
  addRiseLandPoint()
  const markerArr = []
  QJDLIST.forEach((item, index) => {
    let currentdev = qjdevList.find((m) => item.riseLandPointType.includes(m.name))
    let o = {
      id: `riseLand` + index, //maker唯一标识
      coordinate: [Number(item.long), Number(item.lat)], //坐标位置
      coordinateType: 1, //坐标系类型
      imagePath: currentdev
        ? window.origin + currentdev.img
        : `${window.origin}/poi/qjss_jichao.png`,
      anchors: [-25, 50],
      imageSize: [50, 50],
      fixedSize: true,
      range: [0, 20000000], //标签的可见范围 [Min,Max]
      autoHidePopupWindow: true,
      groupId: 'riseLand',
      userData: JSON.stringify(item),
      displayMode: 2, //显示模式
      // priority: 0, //避让优先级
      autoHeight: true,
      occlusionCull: false
    }
    markerArr.push(o)
  })
  console.log(1111111, markerArr)
  await __g.marker.add(markerArr)
  // __g.marker.focusAll(2000, 1, [-24.648006, 49.136005, 0])
  __g.camera.set(535044.517656, 2490617.622822, 5316.796875, -19.70006, -128.61528, 2)
}

// const radar = ref([531241.13, 2500217.92, 4.899375])
const radar = ref([532118.7775, 2500428.64, 7.26572509765625])
const tdjtypes = ['4G/5G设备', '5G-A设备']
//添加通讯基站设备
export async function addTdj() {
  // __g.marker.clear()
  const radiationPointArr = []
  const markerArr = []
  const res = await deviceDeployMap()
  const list = res.data.filter((item) => tdjtypes.includes(item.deployType))
  list.forEach((item, index) => {
    let longLat = item.longLat.split(',')
    let m = {
      id: `equipment` + index, // maker唯一标识
      coordinate: [..._turf.transform([Number(longLat[0]), Number(longLat[1])]), 10], //坐标位置
      coordinateType: 1, // 坐标系类型
      // imagePath: window.origin+'/poi/无人机.png', //图片路径
      imagePath: `${window.origin}/${flyLegendList.find((m) => m.name === item.deployType)?.img}`,
      anchors: [-25, 50],
      imageSize: [50, 50],
      fixedSize: true,
      range: [0, 20000000], //标签的可见范围 [Min,Max]
      autoHidePopupWindow: true,
      groupId: 'equipment',
      userData: JSON.stringify(item),
      displayMode: 2, //显示模式
      priority: 0, //避让优先级
      autoHeight: false,
      occlusionCull: false
    }
    // if (item.deployName !== '001号监视雷达') {
    //   markerArr.push(m)
    // }

    markerArr.push(m)

    // 外圈
    let ro = {
      id: 'radiation-outside' + index,
      coordinate: [Number(longLat[0]), Number(longLat[1])], //坐标位置
      coordinateType: 1, //坐标系类型
      radius: 2000, //辐射半径
      rippleNumber: 5, //波纹数量
      color: [1, 0, 0, 0], //颜色
      intensity: 0.1, //亮度
      autoHeight: true //自动判断下方是否有物体
    }
    // 内圈
    let rw = {
      id: 'radiation-within' + index,
      coordinate: [Number(longLat[0]), Number(longLat[1])], //坐标位置
      coordinateType: 1, //坐标系类型
      radius: 600, //辐射半径
      rippleNumber: 5, //波纹数量
      color: 'red', //颜色
      intensity: 1, //亮度
      autoHeight: true //自动判断下方是否有物体
    }

    if (item.deployType == '光电探测设备') {
      radiationPointArr.push(ro)
      radiationPointArr.push(rw)
    } else if (item.deployType == '频谱探测设备') {
      ro.color = [212 / 255, 207 / 255, 107 / 255]
      radiationPointArr.push(ro)
      radiationPointArr.push(rw)
    }
  })
  // markerArr.push({
  //   id: `equipment11111111111111111111111`, // maker唯一标识
  //   coordinate: radar.value, //坐标位置
  //   coordinateType: 1, // 坐标系类型
  //   // imagePath: window.origin+'/poi/无人机.png', //图片路径
  //   imagePath: `${window.origin}/poi/poi_摄像头@2x.png`,
  //   anchors: [-25, 50],
  //   imageSize: [50, 50],
  //   fixedSize: true,
  //   range: [0, 20000000], //标签的可见范围 [Min,Max]
  //   autoHidePopupWindow: true,
  //   groupId: 'equipmentxx',
  //   userData: JSON.stringify({
  //     deployName: '001号监视雷达',
  //     longLat: '114.26343,22.58698',
  //     deployType: '监视雷达',
  //     type: '通信设备',
  //     coverage: '5000',
  //     companyName: '工信部电子五所',
  //     photo: null,
  //     videoUrl: null,
  //     flightActivities: null
  //   }),
  //   displayMode: 2, //显示模式
  //   priority: 0, //避让优先级
  //   autoHeight: false,
  //   occlusionCull: false
  // })
  await __g.marker.add(markerArr)

  //   await __g.radiationPoint.add(radiationPointArr)
  //   await __g.radiationPoint.add(radiationPointArr)
  // __g.marker.focusAll(2000, 1, [-24.648006, 49.136005, 0])
  __g.camera.set(536039.430937, 2491568.195488, 4685.917812, -19.248243, -123.117661, 2)
}

//添加监视设备
const jsdevtypes = ['5G-A设备', '低空雷达', '光电探测设备']
export async function addJsdev() {
  // __g.marker.clear()
  const radiationPointArr = []
  const markerArr = []
  const res = await deviceDeployMap()
  const list = res.data.filter((item) => jsdevtypes.includes(item.deployType))
  list.forEach((item, index) => {
    let longLat = item.longLat.split(',')
    let m = {
      id: `equipment` + index, // maker唯一标识
      coordinate: [..._turf.transform([Number(longLat[0]), Number(longLat[1])]), 10], //坐标位置
      coordinateType: 1, // 坐标系类型
      // imagePath: window.origin+'/poi/无人机.png', //图片路径
      imagePath: `${window.origin}/${flyLegendList.find((m) => m.name === item.deployType)?.img}`,
      anchors: [-25, 50],
      imageSize: [50, 50],
      fixedSize: true,
      range: [0, 20000000], //标签的可见范围 [Min,Max]
      autoHidePopupWindow: true,
      groupId: 'equipment',
      userData: JSON.stringify(item),
      displayMode: 2, //显示模式
      priority: 0, //避让优先级
      autoHeight: false,
      occlusionCull: false
    }
    markerArr.push(m)
  })
  await __g.marker.add(markerArr)
  popStore.Equipment.showPop = true
  popStore.Equipment.popInfo = list[0]
  popStore.XY = [0, 110]
}

export const showRadio = (e) => {
  if (e.Id === 'equipment11111111111111111111111' || e.Id == 'equipment0') {
    flyNumStore.setRadioShow(true)
    return
  }
}

/**
 * 添加雷达
 */
export const addRadar = async () => {
  flyNumStore.setShowUi(true)
  await __g.marker.hideByGroupId('equipment')
  await __g.weather.setCloudThickness(0)
  await __g.camera.stopAnimation()
  await __g.camera.set(
    [534196.758906, 2495926.679766, 16892.59375, -73.880257, -113.581406, 0.000012],
    1
  )
  __g.customObject.delete('co1')
  const coor = [radar.value[0], radar.value[1], 700]
  //投影坐标
  let co_location = coor
  let o = {
    id: 'co1', //自定义对象唯一id
    pakFilePath: '@path:DTS_Library.pak', //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
    assetPath: '/JC_CustomAssets/EffectLibrary/Exhibition/Point/Point_R_2', //资源目录，自定义对象在pak文件资源包里的相对路径
    location: co_location, //位置坐标
    coordinateType: 0, // 坐标系类型
    rotation: [0, 0, 0], // 世界坐标系旋转
    range: [0, 1000000], //可见范围
    groupId: 'coGroup', //分组id
    localRotation: [0, 0, 0], //模型自身旋转
    scale: [1500, 1500, 1500], //模型缩放
    isEffectRotation: true, //是否开启旋转效果
    smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
    supportAttach: false, //不支持贴画贴合
    visible: true //模型加载后默认是否显示
  }
  await __g.customObject.add(o)

  // [{"idOrPath":"co1","objectType":"CustomObject","objectName":","params":[{"functionName":"H_不透明度","functionParams":[{"name":"V_不透明度","type":3,"defaultValue":1}]},{"functionName":"亮度","functionParams":[{"name":"V_亮度","type":3,"defaultValue":2}]},{"functionName":"速率","functionParams":[{"name":"V_速率","type":3,"defaultValue":1}]},{"functionName":"颜色","functionParams":[{"name":"V_颜色","type":6,"defaultValue":[1,0,0,1]}]}]}]

  __g.customObject.callBPFunction([
    {
      id: 'co1',
      functionName: '颜色',
      parameters: [{ paramType: 6, paramValue: [1, 69 / 255, 0, 1] }]
    }
  ])
}

//添加雷达覆盖范围内的点位
export const addRadarRangeMarker = async () => {
  const list = [
    [114.30695057, 22.60757315],
    [114.29476261, 22.59554865],
    [114.32141304, 22.59665804],
    [114.31866646, 22.59348833],
    [114.30596352, 22.59447887],
    [114.30386066, 22.58916949],
    [114.31484699, 22.58473165]
  ]
  let markerArr = []
  list.forEach((item, index) => {
    let m = {
      id: `equipmentMakerRadar` + index, // maker唯一标识
      coordinate: [..._turf.transform([Number(item[0]), Number(item[1])]), 10], //坐标位置
      coordinateType: 1, // 坐标系类型
      // imagePath: window.origin+'/poi/无人机.png', //图片路径
      imagePath: window.origin + `/poi/qjss_lenged_04.png`,
      anchors: [-25, 50],
      imageSize: [50, 50],
      fixedSize: true,
      range: [0, 20000000], //标签的可见范围 [Min,Max]
      autoHidePopupWindow: true,
      groupId: 'equipmentMakerRadar',
      displayMode: 2, //显示模式
      priority: 0, //避让优先级
      autoHeight: false,
      occlusionCull: false
    }
    markerArr.push(m)
  })
  __g.marker.add(markerArr)
}

/**
 * 获取圆形
 */
function generateCircleCoordinates(center, radius, numPoints) {
  const coordinates = []
  const [centerLng, centerLat] = center // 中心点的经纬度

  // 地球半径（单位：米）
  const EARTH_RADIUS = 6371000

  // 计算每个点的角度增量
  const angleIncrement = (2 * Math.PI) / numPoints

  for (let i = 0; i < numPoints; i++) {
    // 计算当前点的角度
    const angle = i * angleIncrement

    // 计算当前点的偏移量（经度和纬度）
    const offsetLat = (radius / EARTH_RADIUS) * (180 / Math.PI) // 纬度偏移
    const offsetLng =
      ((radius / EARTH_RADIUS) * (180 / Math.PI)) / Math.cos((centerLat * Math.PI) / 180) // 经度偏移

    // 计算当前点的经纬度
    const lat = centerLat + offsetLat * Math.sin(angle)
    const lng = centerLng + offsetLng * Math.cos(angle)

    // 将坐标添加到数组中
    coordinates.push([lng, lat])
  }

  return coordinates
}

export function infrastructureClear() {
  __g.marker.clear(null)
  __g.radiationPoint.clear(null)
  __g.customObject.clear(null)
}

/**
 * 添加起降点图标
 */
export async function addRiseLandPoint() {
  let evtolArr = []
  let jcArr = []
  let qjcArr = []
  QJDLIST.forEach((item, index) => {
    if (item.riseLandPointType.includes('eVtol') || item.riseLandPointType.includes('直升机')) {
      let o = {
        id: 'evtol' + index, //自定义对象唯一id
        pakFilePath: '@path:DTS_Library.pak', //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
        assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/TingJIPin1', //资源目录，自定义对象在pak文件资源包里的相对路径
        location: [Number(item.long), Number(item.lat)], //位置坐标
        coordinateType: 1, // 坐标系类型
        rotation: [0, 70, 0], // 世界坐标系旋转
        range: [0, 100000], //可见范围
        groupId: 'coGroup', //分组id
        localRotation: [0, 0, 0], //模型自身旋转
        scale: [1, 1, 1], //模型缩放
        smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
        autoHeight: true,
        supportAttach: false, //可选，是否支持贴画贴合，默认值：true
        visible: true, //可选，设置自定义对象加载后是否显示，默认：true
        collision: true //可选，设置自定义对象加载后是否开启碰撞，默认：true
      }
      evtolArr.push(o)
    }
    if (item.riseLandPointType.includes('机巢')) {
      let o = {
        id: '机巢' + index, //自定义对象唯一id
        pakFilePath: '@path:DTS_Library.pak', //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
        assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/盐田低空无人机/机舱', //资源目录，自定义对象在pak文件资源包里的相对路径
        location: [Number(item.long), Number(item.lat)], //位置坐标
        coordinateType: 1, // 坐标系类型
        rotation: [0, 0, 0], // 世界坐标系旋转
        range: [0, 100000], //可见范围
        groupId: 'coGroup', //分组id
        localRotation: [0, 55, 0], //模型自身旋转
        scale: [1, 1, 1], //模型缩放
        autoHeight: true,
        smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
        supportAttach: false, //可选，是否支持贴画贴合，默认值：true
        visible: true, //可选，设置自定义对象加载后是否显示，默认：true
        collision: true //可选，设置自定义对象加载后是否开启碰撞，默认：true
      }
      jcArr.push(o)
    }
    if (item.riseLandPointType.includes('起降场')) {
      let o = {
        id: '起降场',
        groupId: 'coGroup', //分组id
        coordinateType: 1, // 坐标系类型
        decalBlendMode: 0, //贴花类型，取值范围：[0,1]；取值说明：0背景混合，1仅贴花（剔除png半透明）；默认值：0
        order: 1, //贴花层级，值越大层级越高，层级最高的显示在最上面一层
        texturePath: `${window.origin}/poi/无人机起降场图片.png`, //贴图文件路径
        location: [Number(item.long), Number(item.lat)],
        rotation: [-90, 125, 0],
        scale: [5, 5, 5]
      }
      qjcArr.push(o)
    }
  })
  await __g.infoTree.deleteByGroupId('coGroup')
  __g.customObject.add(evtolArr.concat(jcArr))
  __g.decal.add(qjcArr)
}
